package com.info3k.client.commands.address;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.ui.Button;
import com.info3k.client.Info3K;
import com.info3k.client.commands.location.NewLocationCommand;
import com.info3k.client.commands.location.UpdateLocationCommand;
import com.info3k.client.components.AddressListWithSearch;
import com.info3k.client.components.AddressRenderer;
import com.info3k.client.components.GlassDialogBox;
import com.info3k.client.domain.Address;
import com.info3k.client.utils.ToolsClient;


public class SelectAddressCommand extends GlassDialogBox implements Command { 
	
	private AddressListWithSearch addressList;
	
	private Command command;
	
	private Info3K info3k;

	public SelectAddressCommand(Command cmd, Info3K info){
		this.info3k = info;
		setCommand(cmd);
		panel.setSize("400px", "450px");
		
		Address[] addresses = null;
		if(command instanceof NewLocationCommand)
			addresses = ((NewLocationCommand)command).getAddresses();
		
		if(command instanceof UpdateLocationCommand)
			addresses = ((UpdateLocationCommand)command).getAddresses();
		
		addressList = new AddressListWithSearch(true, info3k, "350px", addresses);
		content.add(addressList);
		
		setText(Info3K.msgs.selectAddresses());
		
		Button okButton = new Button(Info3K.msgs.ok());
		footer.add(okButton);
		
		okButton.addClickHandler(new ClickHandler(){
			public void onClick(ClickEvent event) {
				hideExtend();
			}
		});
	}

	public void execute() {
		center();
	}
	
	public void hideExtend() {
		List<Address> selectedAddresses = new ArrayList<Address>();
		if(addressList.getAddressRenderers()!=null){
			for (AddressRenderer renderer : addressList.getAddressRenderers()) {
				if(renderer.isAddressSelected()){
					selectedAddresses.add(renderer.getAddress());
				}
			}
		}
		
		if(command instanceof NewLocationCommand)
			((NewLocationCommand)command).setAddresses(ToolsClient.fromCollectionToArray(selectedAddresses, new Address[selectedAddresses.size()]));
		if(command instanceof UpdateLocationCommand)
			((UpdateLocationCommand)command).setAddresses(ToolsClient.fromCollectionToArray(selectedAddresses, new Address[selectedAddresses.size()]));
		hide();
	}

	public void setCommand(Command command) {
		this.command = command;
	}

	public Command getCommand() {
		return command;
	}	
}